package com.cyzy.homework.service.impl;

import com.cyzy.homework.dto.HomeworkDTO;
import com.cyzy.homework.entity.Homework;
import com.cyzy.homework.repository.HomeworkRepository;
import com.cyzy.homework.repository.HomeworkSubmitRepository;
import com.cyzy.homework.service.HomeworkService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 作业服务实现类
 */
@Service
@Transactional
public class HomeworkServiceImpl implements HomeworkService {
    
    @Autowired
    private HomeworkRepository homeworkRepository;
    
    @Autowired
    private HomeworkSubmitRepository homeworkSubmitRepository;
    
    @Override
    public HomeworkDTO createHomework(HomeworkDTO homeworkDTO) {
        Homework homework = new Homework();
        BeanUtils.copyProperties(homeworkDTO, homework);
        // 草稿状态 - 数据库中没有status字段，暂时注释
        homework = homeworkRepository.save(homework);
        return convertToDTO(homework);
    }
    
    @Override
    public HomeworkDTO updateHomework(Long id, HomeworkDTO homeworkDTO) {
        Optional<Homework> optionalHomework = homeworkRepository.findById(id);
        if (!optionalHomework.isPresent()) {
            throw new RuntimeException("作业不存在");
        }
        
        Homework homework = optionalHomework.get();
        homework.setTitle(homeworkDTO.getTitle());
        homework.setContent(homeworkDTO.getContent());
        homework.setDeadline(homeworkDTO.getDeadline());
        // homework.setIsUrgent(homeworkDTO.getIsUrgent()); // 数据库中没有is_urgent字段
        
        homework = homeworkRepository.save(homework);
        return convertToDTO(homework);
    }
    
    @Override
    public void deleteHomework(Long id, String teacherId) {
        Optional<Homework> optionalHomework = homeworkRepository.findByIdAndTeacherId(id, teacherId);
        if (!optionalHomework.isPresent()) {
            throw new RuntimeException("作业不存在或无权限删除");
        }
        
        homeworkRepository.deleteById(id);
    }
    
    @Override
    @Transactional(readOnly = true)
    public HomeworkDTO getHomeworkById(Long id) {
        Optional<Homework> optionalHomework = homeworkRepository.findById(id);
        if (!optionalHomework.isPresent()) {
            throw new RuntimeException("作业不存在");
        }
        
        return convertToDTO(optionalHomework.get());
    }
    
    @Override
    @Transactional(readOnly = true)
    public Page<HomeworkDTO> getAllHomeworks(Pageable pageable) {
        Page<Homework> homeworks = homeworkRepository.findAll(pageable);
        return homeworks.map(this::convertToDTO);
    }
    
    @Override
    @Transactional(readOnly = true)
    public Page<HomeworkDTO> getHomeworksByClassId(String classId, Pageable pageable) {
        Page<Homework> homeworkPage = homeworkRepository.findByClassIdOrderByCreateTimeDesc(classId, pageable);
        return homeworkPage.map(this::convertToDTO);
    }
    
    @Override
    @Transactional(readOnly = true)
    public Page<HomeworkDTO> getHomeworksByTeacherId(String teacherId, Pageable pageable) {
        Page<Homework> homeworkPage = homeworkRepository.findByTeacherIdOrderByCreateTimeDesc(teacherId, pageable);
        return homeworkPage.map(this::convertToDTO);
    }
    
    @Override
    @Transactional(readOnly = true)
    public Page<HomeworkDTO> getHomeworksByClassIdAndStatus(String classId, Integer status, Pageable pageable) {
        // 数据库中没有status字段，暂时忽略status参数，直接按班级查询
        Page<Homework> homeworkPage = homeworkRepository.findByClassIdOrderByCreateTimeDesc(classId, pageable);
        return homeworkPage.map(this::convertToDTO);
    }
    
    @Override
    @Transactional(readOnly = true)
    public Page<HomeworkDTO> getHomeworksByTeacherIdAndStatus(String teacherId, Integer status, Pageable pageable) {
        // 数据库中没有status字段，暂时忽略status参数，直接按教师查询
        Page<Homework> homeworkPage = homeworkRepository.findByTeacherIdOrderByCreateTimeDesc(teacherId, pageable);
        return homeworkPage.map(this::convertToDTO);
    }
    
    @Override
    public HomeworkDTO publishHomework(Long id, String teacherId) {
        Optional<Homework> optionalHomework = homeworkRepository.findByIdAndTeacherId(id, teacherId);
        if (!optionalHomework.isPresent()) {
            throw new RuntimeException("作业不存在或无权限发布");
        }
        
        Homework homework = optionalHomework.get();
        // homework.setStatus(1); // 已发布状态 - 数据库中没有status字段
        homework = homeworkRepository.save(homework);
        return convertToDTO(homework);
    }
    
    @Override
    public HomeworkDTO endHomework(Long id, String teacherId) {
        Optional<Homework> optionalHomework = homeworkRepository.findByIdAndTeacherId(id, teacherId);
        if (!optionalHomework.isPresent()) {
            throw new RuntimeException("作业不存在或无权限结束");
        }
        
        Homework homework = optionalHomework.get();
        // homework.setStatus(2); // 已结束状态 - 数据库中没有status字段
        homework = homeworkRepository.save(homework);
        return convertToDTO(homework);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<HomeworkDTO> getUpcomingDeadline(String classId, int days) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime deadline = now.plusDays(days);
        List<Homework> homeworks = homeworkRepository.findUpcomingDeadline(classId, now, deadline);
        return homeworks.stream().map(this::convertToDTO).collect(Collectors.toList());
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<HomeworkDTO> getExpiredHomeworks(String classId) {
        LocalDateTime now = LocalDateTime.now();
        List<Homework> homeworks = homeworkRepository.findExpired(classId, now);
        return homeworks.stream().map(this::convertToDTO).collect(Collectors.toList());
    }
    
    @Override
    @Transactional(readOnly = true)
    public HomeworkDTO getHomeworkStatistics(Long id) {
        Optional<Homework> optionalHomework = homeworkRepository.findById(id);
        if (!optionalHomework.isPresent()) {
            throw new RuntimeException("作业不存在");
        }
        
        Homework homework = optionalHomework.get();
        HomeworkDTO homeworkDTO = convertToDTO(homework);
        
        // 统计提交情况
        long totalCount = homeworkSubmitRepository.countByHomeworkId(id);
        long submittedCount = homeworkSubmitRepository.countByHomeworkIdAndStatus(id, 1);
        long gradedCount = homeworkSubmitRepository.countByHomeworkIdAndStatus(id, 2);
        
        homeworkDTO.setTotalCount((int) totalCount);
        homeworkDTO.setSubmittedCount((int) submittedCount);
        homeworkDTO.setGradedCount((int) gradedCount);
        
        return homeworkDTO;
    }
    
    @Override
    @Transactional(readOnly = true)
    public boolean isHomeworkBelongsToTeacher(Long id, String teacherId) {
        return homeworkRepository.findByIdAndTeacherId(id, teacherId).isPresent();
    }
    
    @Override
    @Transactional(readOnly = true)
    public boolean isHomeworkBelongsToClass(Long id, String classId) {
        return homeworkRepository.findByIdAndClassId(id, classId).isPresent();
    }
    
    /**
     * 转换为DTO
     */
    private HomeworkDTO convertToDTO(Homework homework) {
        HomeworkDTO homeworkDTO = new HomeworkDTO();
        BeanUtils.copyProperties(homework, homeworkDTO);
        return homeworkDTO;
    }
}
